package com.css.fxfzypg.modules.maps.service.impl;

import com.css.fxfzypg.modules.baseData.entity.PointCityAndArea;
import com.css.fxfzypg.modules.baseData.entity.PointGetDivisionData;
import com.css.fxfzypg.modules.hypergraph.service.HypergraphService;
import com.css.fxfzypg.modules.maps.service.PointGetDivisionService;
import com.css.fxfzypg.util.PlatformObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PointGetDivisionServiceImpl implements PointGetDivisionService  {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Resource
    HypergraphService hypergraphService;

    @Override
    public void resetDivision(String type,String province,String city){
        Thread thread =new Thread(() ->{
            try{
                if(type=="交通（机场）_"){
                    resetAirportData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("sys_airport");
                }
                if(type=="水库_"){
                    resetReservoirData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("data_reservoir");
                }
                if(type=="学校_"){
                    resetSchoolData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("data_school");
                }
                if(type=="医院_"){
                    resetHospitalData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("data_hospital");
                }
                if(type=="地质灾害_"){
                    resetGeologicalData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("data_geological_disasters");
                }
                if(type=="次生灾害危险源（危化企业）_"){
                    resetRiskenterpriseData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("sys_riskenterprisedata");
                }
                if(type=="次生灾害危险源（加油站）_"){
                    resetGasstationData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("sys_gasstationdata");
                }
                if(type=="应急避难场所_"){
                    resetEmergencyshelterData(province,city);
                    //刷新指定超图工作空间数据源数据集
                    boolean bool = hypergraphService.getWorkspaceReload("sys_emergencyshelter");
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        });

        thread.start();
    }

    private List<PointGetDivisionData> getPointGetDivisionDatas(String province,String sql){
        List<PointGetDivisionData> datas = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PointGetDivisionData.class));
        List<PointGetDivisionData> saveDatas=new ArrayList<>();
        for(PointGetDivisionData data : datas){
            PointCityAndArea caa = getCityAndAreaByProvinceAndLonLat(province,data.getLon(),data.getLat());
            if(caa!=null){
                data.setCity(caa.getCityname());
                data.setCounty(caa.getAreaname());
            }
            saveDatas.add(data);
        }

        return saveDatas;
    }

    //机场
    private void resetAirportData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.airport_longitude as lon,a.airport_latitude as lat,a.fileuuid from sys_airport a,qh_map_files b \n" +
                "where b.type='交通（机场）_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update sys_airport set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    //学校
    private void resetSchoolData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.sch_reslongitude as lon,a.sch_reslatitude as lat,a.fileuuid from data_school a,qh_map_files b \n" +
                "where b.type='学校_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update data_school set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    //水库
    private void resetReservoirData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.res_longitude as lon,a.res_latitude as lat,a.fileuuid from data_reservoir a,qh_map_files b \n" +
                "where b.type='水库_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update data_reservoir set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    //医院
    private void resetHospitalData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.dh_longitude as lon,a.dh_latitude as lat,a.fileuuid from data_hospital a,qh_map_files b \n" +
                "where b.type='医院_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update data_hospital set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    //地质灾害隐患点
    private void resetGeologicalData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.dgd_reslongitude as lon,a.dgd_reslatitude as lat,a.fileuuid from data_geological_disasters a,qh_map_files b \n" +
                "where b.type='地质灾害_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update data_geological_disasters set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    //危化企业
    private void resetRiskenterpriseData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.red_longitude as lon,a.red_latitude as lat,a.fileuuid from sys_riskenterprisedata a,qh_map_files b \n" +
                "where b.type='次生灾害危险源（危化企业）_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update sys_riskenterprisedata set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    //加油（加气）站
    private void resetGasstationData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.gs_longitude as lon,a.gs_latitude as lat,a.fileuuid from sys_gasstationdata a,qh_map_files b \n" +
                "where b.type='次生灾害危险源（加油站）_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update sys_gasstationdata set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    //应急避难场所
    private void resetEmergencyshelterData(String province,String city){
        StringBuilder sql = new StringBuilder("select a.id,b.type,a.province,a.city,a.county,a.es_longitude as lon,a.es_latitude as lat,a.fileuuid from sys_emergencyshelter a,qh_map_files b \n" +
                "where b.type='应急避难场所_' and b.province='"+province+"' and a.fileuuid = b.uuid and b.is_delete='0' ");
        if (!PlatformObjectUtils.isEmpty(city) ){
            sql.append(" and b.city='" + city + "'");
        }

        List<PointGetDivisionData> saveDatas=getPointGetDivisionDatas(province,sql.toString());

        if(saveDatas.size()>0){
            String updatesql="update sys_emergencyshelter set city=:city,county=:county where id=:id";
            namedParameterJdbcTemplate.batchUpdate(updatesql, SqlParameterSourceUtils.createBatch(saveDatas.toArray()));
        }
    }

    private PointCityAndArea getCityAndAreaByProvinceAndLonLat(String province,String lon,String lat){
        try {
            if (!PlatformObjectUtils.isEmpty(lon) && !PlatformObjectUtils.isEmpty(lat)) {
                String geomText = "POINT("+lon+" "+lat+")";

                //查询行政区划
                String sql = "select b.name as cityname,b.code as citycode,a.name as areaname,a.code as areacode from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000') " +
                        "where ST_Intersects(a.geom,ST_GeometryFromText('"+geomText+"',4490)) and c.name='"+province+"'" +
                        "order by a.code,b.code,c.code;";

                List<PointCityAndArea> datas = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(PointCityAndArea.class));
                if(datas.size()>0){
                    return datas.get(0);
                }

            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }

        return null;
    }





    /*public List<List<String>> queryProvinceCityCountyNameCodeListByLonLat(String lon,String lat){
        List<List<String>> resultList = new ArrayList<List<String>>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(lon) && !PlatformObjectUtils.isEmpty(lat)) {
                String geomText = "POINT("+lon+" "+lat+")";
                conn = getConnection();
                List<String> nameList = new ArrayList<String>();//行政区划名称列表:省|市|区县|乡镇
                List<String> codeList = new ArrayList<String>();//行政区划编码列表:省|市|区县
                //查询行政区划
                String sql = "select c.name as province,c.code as code1,b.name as city,b.code as code2,a.name as county,a.code as code3 from district_boundary_county a " +
                        "left join district_boundary_city b on b.code=concat(subString(a.code,0,5),'00') " +
                        "left join district_boundary_province c on c.code=concat(subString(a.code,0,3),'0000') " +
                        "where ST_Intersects(a.geom,ST_GeometryFromText('"+geomText+"',4490)) " +
                        "order by a.code,b.code,c.code;";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    String province = rs.getString("province");//行政区划名称--省
                    String city = rs.getString("city");//行政区划名称--市
                    String county = rs.getString("county");//行政区划名称--区县
                    if (!PlatformObjectUtils.isEmpty(province) && !PlatformObjectUtils.isEmpty(city) && !PlatformObjectUtils.isEmpty(county)){
                        String name = province + "-" + city + "-" + county;
                        nameList.add(name);//行政区划名称--省-市-区县
                        String code1 = rs.getString("code1");//行政区划编码--省
                        String code2 = rs.getString("code2");//行政区划编码--市
                        String code3 = rs.getString("code3");//行政区划编码--区县
                        String code = code1 + "-" + code2 + "-" + code3;
                        codeList.add(code);
                    }
                }
                if(nameList.size()>0){
                    resultList.add(nameList);//行政区划名称列表
                    resultList.add(codeList);//行政区划编码列表
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return resultList;
    }*/
}
